#!/usr/bin/python
# -*- coding: UTF-8 -*-

# subversion info:
# $HeadURL: $
# $Author: $
# $Id: $
# $Revision: $

# External imports
from sqlobject import SQLObject, IntCol, UnicodeCol, BoolCol, MultipleJoin, \
    ForeignKey, DateTimeCol
from sqlobject.sqlite import builder
from sqlobject import sqlhub
import datetime

# Internal imports

dbFilename = '/home/skasi/.feedtorrent.db'
sqlhub.processConnection = builder()(dbFilename)

# Episode status
DOWNLOADING = 0
DONEWITHERROR = 4
DONE = 7


class Event(SQLObject):
  date = DateTimeCol(default=datetime.datetime.now)
  title = UnicodeCol(length=256)
  description = UnicodeCol(length=512, default='')
  type = IntCol()
  episode = ForeignKey('Episode', cascade=True)


class Episode(SQLObject):
  number = IntCol()
  title = UnicodeCol(length=512, default='')
  torrentUri = UnicodeCol(length=512)
  status = IntCol(default=DOWNLOADING)
  season = ForeignKey('Season', cascade=True)


class Season(SQLObject):
  number = IntCol()
  episodes = MultipleJoin('Episode')
  tvSerie = ForeignKey('TVSerie', cascade=True)

  def addEpisode(self, episodeNo, title, link):
    for episode in self.episodes:
      if episode.number == episodeNo:
        return None
    else:
      return Episode(number=episodeNo, title=title, torrentUri=link,
          season=self)


class TVSerie(SQLObject):
  name = UnicodeCol(length=256)
  publisher = UnicodeCol(length=256, default=None)
  seasons = MultipleJoin('Season')
  active = BoolCol(default=True)

  def addEpisode(self, seasonNo, episodeNo, title, link):
    if seasonNo is None or episodeNo is None or link is None:
      return None
    title = title or ''
    for season in self.seasons:
      if season.number == seasonNo:
        break
    else:
      season = Season(number=seasonNo, tvSerie=self)
    return season.addEpisode(episodeNo, title, link)

Event.createTable(ifNotExists=True)
Episode.createTable(ifNotExists=True)
Season.createTable(ifNotExists=True)
TVSerie.createTable(ifNotExists=True)

